package net.ithe.controller;

import lombok.extern.slf4j.Slf4j;
import net.ithe.pojo.Result;
import net.ithe.utils.AliyunOSSOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    /**
     * 本地磁盘
     * @param name
     * @param age
     * @param file
     * @return
     */
   /** @PostMapping("/upload")
    public Result upload(String name, Integer age, MultipartFile file) {
        log.info("文件参数{},{},{}", name, age, file);
        //保存文件在本地
        try {
            //这种方式保存文件，存在不足，1.文件名重复，会覆盖。使用UUID解决
           //file.transferTo(new File("D:/images/" + file.getOriginalFilename()));

            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //新的文件名
            //1.获取文件后缀名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + extension;
            //保存
            file.transferTo(new File("D:/images/" + newFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }**/
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件参数{},", file.getOriginalFilename());
        //保存文件
        String url =aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("文件上传oss,url地址{}", url);
        return Result.success(url);
    }
}
